﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlatformGenerator : Singleton<PlatformGenerator> 
{
	protected PlatformGenerator () {}
	
	public Object m_Platforms;
	public float m_PlatformCheckTime = 5.0f;
	public float m_MinAngle = -50.0f;
	public float m_MaxAngle = 10.0f;
	
	private GameObject m_FirstPlatform;
	private float m_FirstOffsetY = 20.0f;
	private GameObject m_LastCreatedPlatform;
	
	private Timer m_CheckPlatformTimer = null;
		
	private void Start () 
	{
		Vector3 firstPos = GameManager.Instance.Marble.transform.position;
		firstPos.y -= GameManager.Instance.Marble.transform.localScale.y + m_FirstOffsetY;
		Quaternion startRotation = new Quaternion(0, 0, 0, 0);
		startRotation.eulerAngles = new Vector3(0, 0 , -20);
		m_LastCreatedPlatform = Instantiate(m_Platforms, firstPos, startRotation) as GameObject;
		m_LastCreatedPlatform.transform.parent = transform;
		
		m_CheckPlatformTimer = TimerManager.Instance.CreateTimer();
	}
	
	private void Update () 
	{
		if(transform.childCount > 0)
		{
			if(m_CheckPlatformTimer.Delta > m_PlatformCheckTime)
			{
				m_CheckPlatformTimer.Reset();
				KillPlatforms();
			}
		}  
		if(m_LastCreatedPlatform.transform.position.x < GameManager.Instance.MainCamera.transform.position.x + GameManager.Instance.HorizontalSize)
		{
			GameObject newPlatform = Instantiate(m_Platforms) as GameObject;
			
			float randomRot = Random.Range(m_MinAngle, m_MaxAngle);
			newPlatform.transform.eulerAngles = new Vector3(0, 0 , randomRot);
			
			Vector3 startPos = newPlatform.transform.GetChildByName("JointA").position;
			Vector3 endPos = m_LastCreatedPlatform.transform.GetChildByName("JointB").position;
			Vector3 deltaPos = endPos - startPos;
			Vector3 newPlatFormPos = newPlatform.transform.position;
			newPlatFormPos += deltaPos;
			newPlatform.transform.position = newPlatFormPos;
			
			m_LastCreatedPlatform = newPlatform;
			m_LastCreatedPlatform.transform.parent = transform;
		}
	}
	
	private void KillPlatforms()
	{		
		for(int i = 0; i < transform.childCount; i++)
		{
			float posToCheck = 	transform.GetChild(i).transform.position.x 	+ 
								GameManager.Instance.HorizontalSize/2 		+ 
								transform.GetChild(i).transform.localScale.x/2;
			if(posToCheck < GameManager.Instance.MainCamera.transform.position.x)
			{
				Destroy(transform.GetChild(i).gameObject);	
			}
		}
	}
}
